﻿using MeetingAssistant.Component.Data.DbInitialize;
using MeetingAssistant.Domain.Model.Member;
using MeetingAssistant.Extension.Common;
using MeetingAssistant.Web;
using System;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MeetingAssistant
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            RouteTable.Routes.RouteExistingFiles = true;//让所有从客户端发送到iis的HTTP请求全部都要经过UrlRoutingModule模块进行路由规则判断的话
            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            ViewEngines.Engines.Add(new WebFormViewEngine());


            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);



            //autofac注册
            RegisterAutofacForSingle.RegisterAutofac();

            //数据库初始化设置
            DatabaseInitializer.Initialize();
        }

       
        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            MyFormsPrincipal<User>.TrySetUserInfo(app.Context);
        }
        /// <summary>
        /// 通过cookie解密，读取用户信息到HttpContext.Current.User
        /// </summary>
        //public void GetUserInfo()
        //{
        //    //读取登录Cookie
        //    HttpCookie cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
        //    try
        //    {
        //        User userData = null;
        //        //解密cookie值，获取FormsAuthenticationTicket对象
        //        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
        //        if (ticket != null && string.IsNullOrEmpty(ticket.UserData) == false)
        //            //还原用户数据
        //            userData = JsonConvert.DeserializeObject<User>(ticket.UserData);
        //        if (ticket != null && userData != null)
        //            //构造我们的MyFormsPrincipal实例，重新给context.User赋值
        //            HttpContext.Current.User = new MyFormsPrincipal<User>(ticket, userData);
        //    }
        //    catch {
        //        //不抛出异常，防止攻击者试探
        //    }
        //}
    }
}
